package org.testopencv;

import com.example.easyscript.dto.BaseMatchResult;
import com.example.easyscript.utils.ImageUtils;
import com.example.easyscript.utils.JnaUtils;
import com.example.easyscript.utils.RobotUtils;
import org.opencv.core.*;
import org.opencv.core.Point;
import org.opencv.highgui.Highgui;
import org.opencv.imgproc.Imgproc;

import java.awt.*;

public class ImageRecognition2 {
    public static void match(String originalFilePath, String templateFilePath) {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

        Mat source, template;
        //将文件读入为OpenCV的Mat格式
        source = Highgui.imread(originalFilePath);
        template = Highgui.imread(templateFilePath);
        //创建于原图相同的大小，储存匹配度
        Mat result = Mat.zeros(source.rows() - template.rows() + 1, source.cols() - template.cols() + 1, CvType.CV_32FC1);
        //调用模板匹配方法
        Imgproc.matchTemplate(source, template, result, Imgproc.TM_CCOEFF_NORMED);
        //规格化
        Core.normalize(result, result, 0, 1, Core.NORM_MINMAX, -1,new Mat());
        //获得最可能点，MinMaxLocResult是其数据格式，包括了最大、最小点的位置x、y
        Core.MinMaxLocResult mlr = Core.minMaxLoc(result,new Mat());
        System.out.println(mlr.minVal);
        System.out.println(mlr.maxVal);
        Point matchLoc = mlr.minLoc;

        //在原图上的对应模板可能位置画一个绿色矩形
        Core.rectangle(source, matchLoc, new Point(matchLoc.x + template.width(), matchLoc.y + template.height()), new Scalar(0, 255, 0));
        //将结果输出到对应位置
        Highgui.imwrite("E:\\easy_script\\src\\main\\resources\\picture\\testspace\\result.png", source);
    }

    public static void main(String[] args) {
        String originalFilePath = "E:\\easy_script\\src\\main\\resources\\picture\\testspace\\img_10.png";
        String templateFilePath = "E:\\easy_script\\src\\main\\resources\\picture\\testspace\\img_8.png";
        match(originalFilePath,templateFilePath);
    }
}
